package com.dimenlink.admin.interceptor;

import com.dimenlink.component.RedisComponent;
import com.dimenlink.entity.constants.Constants;
import com.dimenlink.entity.enums.ResponseCodeEnum;
import com.dimenlink.exception.BusinessException;
import com.dimenlink.utils.StringTools;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppInterceptor implements HandlerInterceptor {
    private static final String URL_ACCOUNT = "/account";
    private static final String URL_FILE = "/file";

    @Resource
    private RedisComponent redisComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(handler ==  null){
            return false;
        }
        /*if(!(handler instanceof HandlerInterceptor)){
            return true;
        }*/
        // 1. 放行不需要认证的路径
        if(request.getRequestURI().contains(URL_ACCOUNT)){
            return true;
        }
        // 2. 获取Token（优先从Header，其次从Cookie）
        String token = request.getHeader(Constants.TOKEN_ADMIN);
        System.out.println("token:"+token);

        // 3. 特殊处理/file路径，支持从Cookie获取Token
        // 获取文件上传的 token
        if(request.getRequestURI().contains(URL_FILE)){
            //token = getTokenFromCookie(request);
            // 如果 Header 中没有 token，再从 Cookie 中获取
            if(StringTools.isEmpty(token)) {
                token = getTokenFromCookie(request);
            }
        }
        // 4. 验证Token有效性
        if(StringTools.isEmpty(token)){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }

        Object sessionObj = redisComponent.getTokenInfo4Admin(token);
        if(sessionObj == null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        return true;
    }

    private String getTokenFromCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return null;
        }
        for(Cookie cookie : cookies){
            if(cookie.getName().equals(Constants.TOKEN_ADMIN)){
                return cookie.getValue();
            }
        }
        return null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
